package vip.wangwenhao.common.util;

import lombok.extern.slf4j.Slf4j;
import vip.wangwenhao.common.constants.CommonConstants;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangwenhao
 */
@Slf4j
public class CookieUtils {

    public static final String DOMAIN = "localhost";
    private static final String PATH = "/";

    public static final int MAX_AGE = 3600 * 24 * 30;
    public static final int MAX_STATE_AGE = 3600;
    /**
     * cookie-info redis  key
     */
    public static final String KEY_LOGIN_INFO = "uim";
    public static final String KEY_LOGIN_STATE = "usm";

    /**
     * 分享邀请来源
     */
    public static final String KEY_SC_S = "sc-s";
    public static final String KEY_SC_S_UID = "sc-s-uid";

    /**
     * 登录信息redis key 前缀
     */
    public static final String REDIS_KEY_LOGIN_INFO = "global:login:";
    /**
     * sms登录信息redis key 前缀
     */
    public static final String REDIS_KEY_LOGIN_STATE = "global:state:";

    /**
     * 获取cookie
     *
     * @param request
     * @param cookieName
     * @return
     */
    public static String getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 设置cookie
     *
     * @param response
     * @param cookieName
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String cookieName, String value) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setDomain(DOMAIN);
        cookie.setPath(PATH);
        cookie.setMaxAge(MAX_AGE);
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     *
     * @param response
     * @param cookieName
     */
    public static void delCookie(HttpServletResponse response, String cookieName) {
        Cookie cookie = new Cookie(cookieName, null);
        cookie.setDomain(DOMAIN);
        cookie.setPath(PATH);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 获取login cookie info
     *
     * @return
     */
    public static String getRequestCookieInfo(HttpServletRequest request) {
        // 先取request cookie 再取 params
        String cookieInfo = CookieUtils.getCookie(request, CommonConstants.UID_COOKIE_KEY);
        if (cookieInfo == null) {
            cookieInfo = request.getParameter(CommonConstants.UID_COOKIE_KEY);
        }
        return cookieInfo;
    }
}
